package dhm.com.hpx.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.ManagerAdapter;
import dhm.com.hpx.adapter.SearchKeyAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.Del;
import dhm.com.hpx.entity.GetManagerBean;
import dhm.com.hpx.entity.ProjectBean;
import dhm.com.hpx.entity.SearchKeyBean;
import dhm.com.hpx.utils.ExcelUtils;
import dhm.com.hpx.utils.ShareUtils;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.Util;

public class ManagerActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.btn_phone)
    RadioButton btnPhone;
    @BindView(R.id.btn_num)
    RadioButton btnNum;
    @BindView(R.id.btn_msg)
    RadioButton btnMsg;
    @BindView(R.id.btn_call)
    RadioButton btnCall;
    @BindView(R.id.recy)
    XRecyclerView recy;
    @BindView(R.id.group)
    RadioGroup group;
    @BindView(R.id.agree)
    CheckBox agree;
    @BindView(R.id.only_phone)
    CheckBox only_phone;
    @BindView(R.id.allnum)
    TextView allnum;
    @BindView(R.id.checknum)
    TextView checknum;
    @BindView(R.id.source)
    TextView source;
    @BindView(R.id.keywordes)
    TextView keywordes;

    private PressenterImpl pressenter;
    private String type;
    private String user_id;

    private int page = 1;
    private List<GetManagerBean.DataBean.ListDataBean> managerList;
    private ManagerAdapter adapter;

    Map<String, String> map;

    private List<String> sourcelist = new ArrayList<>();
    private OptionsPickerView pvOptions;
    private SearchKeyBean searchKeyBean;

    private PopupWindow popWindow;
    private boolean onlyPhone = false;

    private String userType;

    @Override
    protected int getLayout() {
        return R.layout.activity_manager;
    }

    private IWXAPI api;
    @Override
    protected void initView() {

        ButterKnife.bind(this);
        userType = SpUtils.getString(this, "userType");
        pressenter = new PressenterImpl();
        pressenter.attachView(this);
        api = WXAPIFactory.createWXAPI(this, Constant.Wx_APP_ID, false);
        sourcelist.clear();
        sourcelist.add("全图客源");
        sourcelist.add("分类客源");
        sourcelist.add("范围客源");

        type = getIntent().getStringExtra("type");
        user_id = SpUtils.getString(this, "uid");
        page = 1;

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy.setLayoutManager(manager);
        recy.setPullRefreshEnabled(true);
        recy.setLoadingMoreEnabled(true);

        recy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                map.put("page", page + "");
                pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
            }

            @Override
            public void onLoadMore() {
                map.put("page", page + "");
                pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
            }
        });

        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.btn_phone:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_export_table", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_num:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_export_mail", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_msg:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_sms", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_call:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_phone", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    default:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                }
            }
        });

    }

    @Override
    protected void initData() {
        showPopwindow();
    }

    @Override
    protected void onResume() {
        super.onResume();
        map = new HashMap<>();
        map.put("customer_type", type);
        map.put("token", Constant.TOKEN);
        map.put("uid", user_id);
        showProgressDialog();
        pressenter.sendMessage(this, Constant.search_count, map, SearchKeyBean.class);
    }

    private ProgressDialog progDialog = null;// 搜索时进度条


    private void checknum() {
        if (managerList == null || managerList.size() == 0) {
            return;
        }

        int num = 0;
        for (int i = 0; i < managerList.size(); i++) {
            if (managerList.get(i).getIscheck().equals("1")) {
                num++;
            }
        }
        checknum.setText(num + "");

    }

    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private int REQUEST_PERMISSION_CODE = 1000;


    private String filePath = "/sdcard/quqike";

    @OnClick({R.id.back, R.id.agree, R.id.only_phone, R.id.lin_num, R.id.lin_excel, R.id.lin_msg, R.id.lin_del, R.id.lin_source, R.id.lin_key, R.id.lin_status, R.id.lin_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lin_source: //选择地址
                pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        source.setText(sourcelist.get(options1));
                        checkKay="";
                        keywordes.setText("关键字");
                        type = (options1 + 1) + "";
                        page=1;
                        map = new HashMap<>();
                        map.put("customer_type", type);
                        map.put("token", Constant.TOKEN);
                        map.put("uid", user_id);
                        showProgressDialog();
                        pressenter.sendMessage(ManagerActivity.this, Constant.search_count, map, SearchKeyBean.class);
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(sourcelist);
                pvOptions.show();
                break;
            case R.id.lin_key:
                if (popupWindows != null) {
                    setBackgroundAlpha(0.5f);
                    popupWindows.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                } else {
                    Toast.makeText(this, "您还没有搜索关键词记录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.back:
                finish();
                break;
            case R.id.lin_clear:


                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:
                        //权限没有获得
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            // 不需要解释为何需要该权限，直接请求授权
                            // 不需要解释为何需要该权限，直接请求授权
                            ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS}, 100);
                        } else {
// 获得所有的联系人
                            try {
                                showProgressDialog();
                                Cursor cursor = getContentResolver().query(
                                        ContactsContract.Contacts.CONTENT_URI,
                                        null,
                                        null,
                                        null,
                                        ContactsContract.Contacts.DISPLAY_NAME
                                                + " COLLATE LOCALIZED ASC");
                                List<Del> phoneList = new ArrayList<>();
                                while (cursor.moveToNext()) {

                                    //新建一个联系人实例
                                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                                    if (name!=null&&name.length() > 4) {
                                        String substring = name.substring(0, 4);
                                        if (substring.equals("QQK_")) {

                                            String contactId = cursor.getString(cursor
                                                    .getColumnIndex(ContactsContract.Contacts._ID));
                                            //获取联系人所有电话号
                                            Cursor phones = getContentResolver().query(
                                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                    null,
                                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                                                            + contactId, null, null);
                                            while (phones.moveToNext()) {

                                                String phoneNumber = phones
                                                        .getString(phones
                                                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                                phoneList.add(new Del(name, phoneNumber));
                                            }
                                            phones.close();
                                        }

                                    }

                                }
                                for (int i = 0; i < phoneList.size(); i++) {
                                    deleteContact(this, phoneList.get(i).getPhone(), phoneList.get(i).getName());
                                }
                                dissmissProgressDialog();
                                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                            }catch (Exception e){
                                Toast.makeText(this, "问题所在："+e.toString(), Toast.LENGTH_SHORT).show();
                            }
                        }
                }


                break;
            case R.id.agree:
                if (managerList==null||managerList.size()==0){
                    Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (agree.isChecked()) {
                    for (int i = 0; i < managerList.size(); i++) {
                        managerList.get(i).setIscheck("1");
                    }
                } else {
                    for (int i = 0; i < managerList.size(); i++) {
                        managerList.get(i).setIscheck("0");
                    }

                }
                checknum();
                adapter.setList(managerList);
                break;
            case R.id.only_phone:
                if (managerList==null||managerList.size()==0){
                    Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (only_phone.isChecked()) {
                    onlyPhone = true;
                    onlyPhone();
                } else {
                    onlyPhone = false;
                    adapter.setList(managerList);
                }

                break;
            case R.id.lin_num:


                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:
                        //权限没有获得
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                            // 不需要解释为何需要该权限，直接请求授权
                            ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS}, 100);
                        } else {
                            // 已经获得授权
//                    Util.addContact(this,"小萌芽","18801586942");
                            try {
                                showProgressDialog();
                                boolean isdao = false;
                                String id = "";
                                if (managerList==null||managerList.size()==0){
                                    Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                                    dissmissProgressDialog();
                                    return;
                                }

                                for (int i = 0; i < managerList.size(); i++) {
                                    if (managerList.get(i).getIscheck().equals("1")) {
                                        id = id + managerList.get(i).getCustomer_id() + ",";

                                        String[] split = managerList.get(i).getTel().split(";");
                                        for (int j = 0; j < split.length; j++) {
                                            isdao = true;
                                            Util.addContact(this, "QQK_" + managerList.get(i).getCompany_name() + (j + 1), split[j]);
                                        }
                                    }
                                }

                                if (isdao) {
                                    id = id.substring(0, id.length() - 1);
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", Constant.TOKEN);
                                    map.put("uid", user_id);
                                    map.put("type", "2");
                                    map.put("customer_id", id);
                                    map.put("status", "1");
                                    map.put("customer_type", type);
                                    pressenter.sendMessage(this, Constant.modify_status, map, Bean.class);

                                    dissmissProgressDialog();
                                    Toast.makeText(this, "导入成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    dissmissProgressDialog();
                                    Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                                }

                            }catch (Exception e){
                                Toast.makeText(this, "问题所在："+e.toString(), Toast.LENGTH_SHORT).show();
                            }
                        }

                }


                break;
            case R.id.lin_excel:
                filePath = "/sdcard/quqike";
                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:

                        if (Build.VERSION.SDK_INT > 23) {
                            if (ContextCompat.checkSelfPermission(this, permissions[0])
                                    == PackageManager.PERMISSION_GRANTED) {
                                //授予权限
                                showProgressDialog();
                                File file = new File(filePath);
                                if (!file.exists()) {
                                    file.mkdirs();
                                }


                                String excelFileName = "/demo.xls";


                                String[] title = {"公司名称", "联系方式", "地址"};
                                String sheetName = "demoSheetName";

                                String id = "";
                                List<ProjectBean> demoBeanList = new ArrayList<>();
                                for (int i = 0; i < managerList.size(); i++) {
                                    if (managerList.get(i).getIscheck().equals("1")) {
                                        id = id + managerList.get(i).getCustomer_id() + ",";
                                        ProjectBean projectBean = new ProjectBean();
                                        projectBean.setName(managerList.get(i).getCompany_name());
                                        projectBean.setPhone(managerList.get(i).getTel());
                                        projectBean.setAddress(managerList.get(i).getProvince() + managerList.get(i).getCity() + managerList.get(i).getArea() + managerList.get(i).getAddress());
                                        demoBeanList.add(projectBean);
                                    }

                                }
                                if (demoBeanList == null || demoBeanList.size() == 0) {
                                    Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                                    dissmissProgressDialog();
                                    return;
                                }


                                filePath = filePath + excelFileName;


                                ExcelUtils.initExcel(filePath, sheetName, title);


                                ExcelUtils.writeObjListToExcel(demoBeanList, filePath, this);
                                id = id.substring(0, id.length() - 1);
                                Map<String, String> map = new HashMap<>();
                                map.put("token", Constant.TOKEN);
                                map.put("uid", user_id);
                                map.put("type", "1");
                                map.put("customer_id", id);
                                map.put("status", "1");
                                map.put("customer_type", type);
                                pressenter.sendMessage(this, Constant.modify_status, map, Bean.class);
                                dissmissProgressDialog();
                                Toast.makeText(this, "excel已导出至：" + filePath, Toast.LENGTH_SHORT).show();
                                ShareFileToWeiXin(filePath);

                            } else {
                                //未获得权限
                                requestPermissions(permissions, REQUEST_PERMISSION_CODE);
                            }
                        } else {
                            showProgressDialog();
                            File file = new File(filePath);
                            if (!file.exists()) {
                                file.mkdirs();
                            }


                            String excelFileName = "/demo.xls";


                            String[] title = {"公司名称", "联系方式", "地址"};
                            String sheetName = "demoSheetName";

                            String id = "";
                            List<ProjectBean> demoBeanList = new ArrayList<>();
                            for (int i = 0; i < managerList.size(); i++) {
                                if (managerList.get(i).getIscheck().equals("1")) {
                                    id = id + managerList.get(i).getCustomer_id() + ",";
                                    ProjectBean projectBean = new ProjectBean();
                                    projectBean.setName(managerList.get(i).getCompany_name());
                                    projectBean.setPhone(managerList.get(i).getTel());
                                    projectBean.setAddress(managerList.get(i).getProvince() + managerList.get(i).getCity() + managerList.get(i).getArea() + managerList.get(i).getAddress());
                                    demoBeanList.add(projectBean);
                                }

                            }
                            if (demoBeanList == null || demoBeanList.size() == 0) {
                                Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                                dissmissProgressDialog();
                                return;
                            }


                            filePath = filePath + excelFileName;


                            ExcelUtils.initExcel(filePath, sheetName, title);


                            ExcelUtils.writeObjListToExcel(demoBeanList, filePath, this);
                            id = id.substring(0, id.length() - 1);
                            Map<String, String> map = new HashMap<>();
                            map.put("token", Constant.TOKEN);
                            map.put("uid", user_id);
                            map.put("type", "1");
                            map.put("customer_id", id);
                            map.put("status", "1");
                            map.put("customer_type", type);
                            pressenter.sendMessage(this, Constant.modify_status, map, Bean.class);
                            dissmissProgressDialog();
                            Toast.makeText(this, "excel已导出至：" + filePath, Toast.LENGTH_SHORT).show();
                            ShareFileToWeiXin(filePath);
                        }
                }


                break;
            case R.id.lin_msg:

                switch (userType) {
                    case "0":
                        Toast.makeText(this, "暂无权限查看，请升级会员", Toast.LENGTH_SHORT).show();
                        break;
                    case "4":
                        Toast.makeText(this, "您的会员已过期", Toast.LENGTH_SHORT).show();
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "5":
                    default:

                        String id = "";
                        String phone = "";
                        for (int i = 0; i < managerList.size(); i++) {
                            if (managerList.get(i).getIscheck().equals("1")) {
                                id = id + managerList.get(i).getCustomer_id() + ",";
                                phone = phone + managerList.get(i).getTel() + ";";
                            }
                        }
                        if (phone == null || phone.equals("")) {
                            Toast.makeText(this, "请选择群发商家", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        id = id.substring(0, id.length() - 1);
                        phone = phone.substring(0, phone.length() - 1);

                        Intent intent = new Intent(this, MsgActivity.class);
                        intent.putExtra("phone", phone);
                        startActivity(intent);
                        Map<String, String> map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("uid", user_id);
                        map.put("type", "4");
                        map.put("customer_id", id);
                        map.put("status", "1");
                        map.put("customer_type", type);
                        pressenter.sendMessage(this, Constant.modify_status, map, Bean.class);

                }


                break;
            case R.id.lin_del:
                Map<String, String> map1 = new HashMap<>();
                map1.put("token", Constant.TOKEN);
                map1.put("uid", user_id);

                pressenter.sendMessage(this, Constant.clear_all, map1, Bean.class);

                break;
            case R.id.lin_status:
                setBackgroundAlpha(0.5f);
                popWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
                break;
            default:
        }
    }

    private void onlyPhone() {
        for (int i = 0; i < managerList.size(); i++) {
            String tel = managerList.get(i).getTel();
            String substring = tel.substring(0, 1);
            if (substring.equals("0")) {
                managerList.remove(i);
                i--;
            }
        }
        adapter.setList(managerList);
    }

    public static boolean deleteContact(Context ctx, String phone, String name) {
        Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
        try {
            if (cur.moveToFirst()) {
                do {
                    if (cur.getString(cur.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                        String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                        ctx.getContentResolver().delete(uri, null, null);
                        return true;
                    }

                } while (cur.moveToNext());
            }

        } catch (Exception e) {
            Toast.makeText(ctx, e.getStackTrace()+"", Toast.LENGTH_SHORT).show();
        } finally {
            cur.close();
        }
        return false;
    }


    private AlertDialog alertDialog;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showProgressDialog();
                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }


                String excelFileName = "/demo.xls";


                String[] title = {"公司名称", "联系方式", "地址"};
                String sheetName = "demoSheetName";

                String id = "";
                List<ProjectBean> demoBeanList = new ArrayList<>();
                for (int i = 0; i < managerList.size(); i++) {
                    if (managerList.get(i).getIscheck().equals("1")) {
                        id = id + managerList.get(i).getCustomer_id() + ",";
                        ProjectBean projectBean = new ProjectBean();
                        projectBean.setName(managerList.get(i).getCompany_name());
                        projectBean.setPhone(managerList.get(i).getTel());
                        projectBean.setAddress(managerList.get(i).getProvince() + managerList.get(i).getCity() + managerList.get(i).getArea() + managerList.get(i).getAddress());
                        demoBeanList.add(projectBean);
                    }

                }
                if (demoBeanList == null || demoBeanList.size() == 0) {
                    Toast.makeText(this, "请选择商家", Toast.LENGTH_SHORT).show();
                    dissmissProgressDialog();
                    return;
                }


                filePath = filePath + excelFileName;


                ExcelUtils.initExcel(filePath, sheetName, title);


                ExcelUtils.writeObjListToExcel(demoBeanList, filePath, this);
                id = id.substring(0, id.length() - 1);
                Map<String, String> map = new HashMap<>();
                map.put("token", Constant.TOKEN);
                map.put("uid", user_id);
                map.put("type", "1");
                map.put("customer_id", id);
                map.put("status", "1");
                map.put("customer_type", type);
                pressenter.sendMessage(this, Constant.modify_status, map, Bean.class);
                dissmissProgressDialog();
                Toast.makeText(this, "excel已导出至：" + filePath, Toast.LENGTH_SHORT).show();
                ShareFileToWeiXin(filePath);

            } else {
                Log.i("onPermissionsResult:", "用户拒绝了权限申请");
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("permission")
                        .setMessage("点击允许才可以使用我们的app哦")
                        .setPositiveButton("去允许", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                if (alertDialog != null && alertDialog.isShowing()) {
                                    alertDialog.dismiss();
                                }
                                ActivityCompat.requestPermissions(ManagerActivity.this,
                                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                            }
                        });
                alertDialog = builder.create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
        }
    }

    private int positions = 0;


    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null) {
            progDialog = new ProgressDialog(this);
        }
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在加载...");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }


    @Override
    public void requesta(Object data) {
        if (data instanceof SearchKeyBean) {
            searchKeyBean = (SearchKeyBean) data;
            if (searchKeyBean.getCode() == 1) {
                showPopwindows();
            }

            page=1;
            map = new HashMap<>();
            map.put("token", Constant.TOKEN);
            map.put("page", page + "");
            map.put("type", type + "");
            map.put("user_id", user_id + "");
            map.put("checkKay", checkKay);
            pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);

        } else if (data instanceof GetManagerBean) {
            GetManagerBean getManagerBean = (GetManagerBean) data;
            if (getManagerBean.getCode() == 1) {
                if (page == 1) {
                    allnum.setText(getManagerBean.getData().getCount() + "");
                    recy.setVisibility(View.VISIBLE);
                    managerList = getManagerBean.getData().getList_data();

                    adapter = new ManagerAdapter(this, user_id);
                    adapter.setdeleteClick(new ManagerAdapter.OnClick() {
                        @Override
                        public void item(int posttion, boolean check) {
                            if (check) {
                                managerList.get(posttion).setIscheck("1");
                            } else {
                                managerList.get(posttion).setIscheck("0");
                            }
                            checknum();
                            adapter.setList(managerList);
                        }
                    });

                    adapter.setaddClick(new ManagerAdapter.OnIntentClick() {
                        @Override
                        public void item(int position) {

                            positions = position;
                            Map<String, String> map = new HashMap<>();
                            map.put("token", Constant.TOKEN);
                            map.put("uid", user_id);
                            map.put("customer_id", managerList.get(position).getCustomer_id() + "");

                            pressenter.sendMessage(ManagerActivity.this, Constant.customercollectdel, map, Bean.class);

                        }
                    });


                    recy.setAdapter(adapter);
                } else {
                    managerList.addAll(getManagerBean.getData().getList_data());
                }
                page++;
                checknum();
                if (onlyPhone) {
                    onlyPhone();
                } else {
                    adapter.setList(managerList);
                }

            } else {
                if (page == 1) {
                    recy.setVisibility(View.GONE);
                }
                Toast.makeText(this, getManagerBean.getMessage(), Toast.LENGTH_SHORT).show();
            }
            recy.loadMoreComplete();
            recy.refreshComplete();
            dissmissProgressDialog();
        } else if (data instanceof Bean) {
            Bean bean = (Bean) data;
            if (bean.getCode() == 1) {
                Toast.makeText(this, bean.getMessage(), Toast.LENGTH_SHORT).show();
                if (bean.getMessage().equals("清空成功")) {
                    page = 1;
                    managerList.clear();
                    adapter.setList(managerList);
                } else if (bean.getMessage().equals("删除成功")) {
                    managerList.remove(positions);
                    adapter.setList(managerList);
                }
            }
        }
    }

    @Override
    public void fail(String error) {
        dissmissProgressDialog();
        if (error.equals("timeout")){
            Toast.makeText(this, "服务器连接超时", Toast.LENGTH_SHORT).show();
        }
    }

    private String checkKay = "";

    private PopupWindow popupWindows;

    private void showPopwindows() {
        View popView = View.inflate(this, R.layout.search_key, null);
        TextView sure = popView.findViewById(R.id.sure);
        TextView cancle = popView.findViewById(R.id.cancle);
        RecyclerView recy_hot = popView.findViewById(R.id.recy_hot);

        GridLayoutManager manager = new GridLayoutManager(this, 4);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_hot.setLayoutManager(manager);
        final SearchKeyAdapter adapter = new SearchKeyAdapter(this);
        recy_hot.setAdapter(adapter);

        adapter.setdeleteClick(new SearchKeyAdapter.OnClick() {
            @Override
            public void item(int posttion) {
                for (int i = 0; i < searchKeyBean.getData().size(); i++) {
                    searchKeyBean.getData().get(i).setParam_check("0");
                }
                checkKay = searchKeyBean.getData().get(posttion).getSearch_key();
                searchKeyBean.getData().get(posttion).setParam_check("1");
                adapter.setList(searchKeyBean.getData());

            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindows.dismiss();
            }
        });
        adapter.setList(searchKeyBean.getData());

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                keywordes.setText(checkKay);
                switch (group.getCheckedRadioButtonId()) {
                    case R.id.btn_phone:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_export_table", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_num:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_export_mail", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_msg:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_sms", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    case R.id.btn_call:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("no_phone", "1");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                        break;
                    default:
                        page = 1;
                        map = new HashMap<>();
                        map.put("token", Constant.TOKEN);
                        map.put("page", page + "");
                        map.put("type", type + "");
                        map.put("user_id", user_id + "");
                        map.put("checkKay", checkKay);
                        pressenter.sendMessage(ManagerActivity.this, Constant.customercollect_customer_list, map, GetManagerBean.class);
                }
                popupWindows.dismiss();
            }
        });

        popupWindows = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setFocusable(true);
        popupWindows.setTouchable(true);
        popupWindows.setBackgroundDrawable(new BitmapDrawable());
        popupWindows.setOutsideTouchable(true);// 设置允许在外点击消失

        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }



    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }


    private void showPopwindow() {
        View popView = View.inflate(this, R.layout.dialog_status, null);
        Button cancle = popView.findViewById(R.id.cancle);

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popWindow.dismiss();
            }
        });
        popWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);// 设置允许在外点击消失

        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // popupWindow隐藏时恢复屏幕正常透明度
                setBackgroundAlpha(1.0f);
            }
        });

    }



    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }



    private void ShareFileToWeiXin(String filePath) {

        File file = new File(filePath);

/*

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            StrictMode.VmPolicy.Builder builder=new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }


        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-excel");
        startActivity(intent);

*/



        ShareUtils.shareWechatFriend(ManagerActivity.this,file);

//
//        Toast.makeText(this, file.exists()+"", Toast.LENGTH_SHORT).show();
//
//        WXFileObject fileObject = new WXFileObject();
//        fileObject.setContentLengthLimit(1024*1024*10);
//
//        fileObject.setFilePath(filePath);//设置文件本地地址
//
//        WXMediaMessage msg = new WXMediaMessage();
//
//        msg.mediaObject= fileObject;
//        msg.title= "demo.xls";
//
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//
//        req.transaction= buildTransaction("file");
//
//        req.message= msg;
//
//        req.scene= SendMessageToWX.Req.WXSceneSession;
//
////        LogUtils.i("SendToWXActivity","mTargetScene---"+ buildTransaction("file") +"---"+ msg);
//
//        api.sendReq(req);

      /*
        WXFileObject fileObj = new WXFileObject();
        fileObj.fileData = WXUtil.inputStreamToByte(filePath);//文件路径  
        fileObj.filePath = filePath;
        //使用媒体消息分享
        WXMediaMessage msg = new WXMediaMessage(fileObj);
        msg.title = "demo.xls";
        //发送请求  
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        //创建唯一标识  
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);*/
    }


    /**
     * 获取指定文件大小
     *
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) {
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } else {
                file.createNewFile();
                Log.e("获取文件大小", "文件不存在!");
            }
            return size;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }



}
